package com.xuliugen.demo.multithread.treadlocal;

import java.lang.ref.WeakReference;

/**
 * Created by xuliugen on 2017/11/13.
 */
public class WeakReferenceDemo {

    public static void main(String[] args) throws InterruptedException {
        User user = new User("xuliugen", "123456");
        WeakReference<Object> weakReference = new WeakReference<>(user);
        //obj = null;

        for (int i = 1; i <= 2; i++) {
            new Thread(() -> {
                //-Xms20m -Xmx20m -Xmn10m -XX:+PrintGCDetails -XX:SurvivorRatio=8
                byte[] allocation1, allocation2, allocation3, allocation4;
                allocation1 = new byte[3 * 1024 * 1024];
                allocation2 = new byte[3 * 1024 * 1024];
                allocation3 = new byte[3 * 1024 * 1024];
                allocation4 = new byte[4 * 1024 * 1024];
                System.out.println(allocation1.length);
            }).start();
            Thread.sleep(2000);
        }

        System.out.println(weakReference.get().toString());//有时候会返回null
        System.out.println(weakReference.isEnqueued());
    }

    public static class User {
        private String userName;
        private String userPwd;

        public User(String userName, String userPwd) {
            this.userName = userName;
            this.userPwd = userPwd;
        }

        @Override
        public String toString() {
            return "User{" +
                    "userName='" + userName + '\'' +
                    ", userPwd='" + userPwd + '\'' +
                    '}';
        }
    }
}
